import {Button, message, Tag} from 'antd';
import React, {useState, useRef} from 'react';
import {PageContainer, FooterToolbar} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import DnsDetailsForm from './components/dnsDetailsForm';
import { queryDomainList, removeRule, sysncu } from './service';
import './monitor.less'


/**
 *  删除节点
 * @param selectedRows
 */

const handleRemove = async selectedRows => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeRule({
      idList: selectedRows.map(row => row.id),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
//
// const handleUpdate = async fields => {
//   const hide = message.loading('正在更新');
//   try {
//     await updateUser(fields);
//     hide();
//     message.success('更新成功');
//     return true;
//   } catch (error) {
//     hide();
//     message.error('更新失败请重试！');
//     return false;
//   }
// };

const dnsTableList = () => {
  const actionRef = useRef();
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const [selectedRowsState, setSelectedRows] = useState([]);

  /**
   * 用户同步
   * @returns {Promise<boolean>}
   */
  const  handleAccountSysnc = async () =>{
    const hide = message.loading('正在同步数据');
    try{
      await sysncu();
      hide();
      message.success('数据同步成功');
      if (actionRef.current) {
        actionRef.current.reload();
      }
      return true;
    }catch (e) {
      hide();
      message.error('数据同步失败请重试！');
      return false;
    }
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      sorter: true
    },
    {
      title: '域名名称',
      key: 'name',
      dataIndex: 'name',
    },
    {
      title: '所属公司',
      key: 'registrantOrganization',
      dataIndex: 'registrantOrganization',
    },
    {
      title: '状态',
      key: 'isAvailable',
      dataIndex: 'isAvailable',
      render: (text, record) => {
        const color = record.isAvailable === "1" ? "green" : "red";
        return (
          <Tag color={color} key={record.isAvailable}>
            {
              text === "1" ? "可用" : "不可用"
            }
          </Tag>
        );
      }
    },
    {
      title: '认证状态',
      key: 'realNameStatus',
      dataIndex: 'realNameStatus'
    },
    {
      title: '剩余天数',
      key: 'daysRemaining',
      dataIndex: 'daysRemaining',
      render: (text, record) => {
        return (
          <Tag color="green" key={record.daysRemaining}>
            {
              `${text} 天`
            }
          </Tag>
        );
      }
    },
    {
      title: '注册人',
      key: 'registrantName',
      dataIndex: 'registrantName'
    },
    {
      title: '注册时间',
      key: 'registryTime',
      dataIndex: 'registryTime',
      sorter: true,
      valueType: 'dateTime'
    },
    {
      title: '操作',
      key: 'option',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleUpdateModalVisible(true);
              setStepFormValues(record);
            }}
          >
            解析
          </a>
        </>
      ),
    },
  ];

  return (

    <PageContainer>
      <ProTable
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="key"
        toolBarRender={() => [
          <Button type="primary" onClick={() => handleAccountSysnc()}>
            同步
          </Button>,
        ]}
        request={(params, sorter, filter) => queryDomainList({...params, sorter, filter})}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项
            </div>
          }
        >
          <Button
            type="primary"
            danger
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}


      {stepFormValues && Object.keys(stepFormValues).length ? (
        <DnsDetailsForm
          key="dnsList"
          onCancel={() => {
            handleUpdateModalVisible(false);
            setStepFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={stepFormValues}
        />
      ) : null}

    </PageContainer>
  );
};

export default dnsTableList;
